package com.group2.operations.shiro;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

public class MyWebSessionManager extends DefaultWebSessionManager{
    private static final String AUTH_TOKEN = "authToken";

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        System.out.println("=======MyWebSessionManager========");

        //从请求头中获取sessionID
        String sessionId = WebUtils.toHttp(request).getHeader(AUTH_TOKEN);
        //若为空则调用父类方法，从cookie中取
        if(StringUtils.isEmpty(sessionId)) {
            return super.getSessionId(request, response);
        }
        else {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "stateless");
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, true);
            return sessionId;
        }
    }
}
